<?php

namespace app\index\controller;

use mikkle\tp_wechat\support\Curl;
use mikkle\tp_wechat\Wechat;

class User extends Common
{
    public function getInfo()
    {
        $uid = $this->isCheckAuth();
      //  $userId = trim(input('userId'));
        $db = db('user');
       /* if($userId){
            $data = $db->field('id,nickname,headurl')->where(['id' => $userId])->find();
        }else{

        }*/
        $data = $db->field('id,nickname,headurl')->where(['id' => $uid])->find();
        $this->rest($data);
    }


    /**
     * 用户统一登录
     */
    public function login()
    {
        //type 登录类型[user：帐号密码登录、mini：小程序登录、wx：微信公众号、wxapp：微信APP登录]
        $type = input("type/s");
        if (!$type) {
            $this->rest('登录类型错误', 's004');
        }
        switch ($type){
            case "user":
                $this->userLogin();
                break;
            case "mini":
                $this->getMiniUser();
                break;
        }
    }

    /**
     * 用户账号密码登录(废除)
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function userLogin()
    {
        $username = input("post.username");
        $password = input("post.password");
        if ($username == "" || $username == "") {
            exit(json_encode(["data" => "", "code" => "s004", "message" => "用户名和密码不能为空"], JSON_UNESCAPED_UNICODE));
        }

        $userData = db("users")->field("u.user_id as userId,'' as token,nickname,head_pic as headPic,mobile")->alias("u")->where(["u.username" => $username, "u.password" => $password])->find();
        if ($userData){
            //登录成功修改token,首先判断token是否存在
            $tokenDb = db("api_user_token");
            $token = md5($username . $password . $userData['userId'] . time());
            $tokenData = array(
                "token" => $token,
                "time" => time(),
                "ipaddress" => $_SERVER["REMOTE_ADDR"],
                "action_token" => $token,
                "user_id" => $userData["userId"]
            );
            if ($tokenDb->where("user_id", $userData["userId"])->find()) {
                $tokenDb->where("user_id", $userData["userId"])->update($tokenData);
            } else {
                $tokenDb->insert($tokenData);
            }
            $userData["token"] = $token;
            $array = array(
                "data" => $userData,
                "code" => "0000",
                "message" => "登录成功"
            );
            exit(json_encode($array, JSON_UNESCAPED_UNICODE));
        } else {
            exit(json_encode(["data" => "", "code" => "s004", "message" => "用户名或密码错误"], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 微信小程序登录
     * @throws \mikkle\tp_wechat\support\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function miniOauth()
    {
        if (!input('post.code')) {
            $this->rest('code获取失败', 's004');
        }
        $wechat = new Wechat();
        $code = input('post.code');
        $token = $wechat->oauth()->getOauthAccessToken($code);
        if (!$token) {
            $this->rest('accessToken获取失败', 's004');
        }
        $userInfo = $wechat->oauth()->getOauthUserInfo($token['access_token'], $token['openid']);
        $data = db('user')->alias("u")->join('user_token ut', 'u.id = ut.uid')->where('openid_mini', $token['openid'])->find();
        if (!$data) {
            $data = array(
                'openid_mini' => $userInfo['openid'],
                'nickname' => filter_Emoji($userInfo['nickname']),
                'headurl' => $userInfo['headimgurl'],
                'sex' => $userInfo['sex'],
                'address' => $userInfo['address'],
            );
            $userId = $this->regUser($data);
        } else {
            $userId = $data['id'];
        }
        $token = update_user_token($userId);
        $result = array(
            'userId' => $userId,
            'userName' => '',
            'headUrl' => $data['headurl'],
            'token' => $token
        );
        $this->rest($result);

    }

    /**
     * 微信APP登录（未优化）
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function weChatLogin()
    {
        $code = input('code');
        $appid = "wxe910984b126d7fde";
        $secret = "73dda5217a101b91289377157c72c28c";
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $sContent = json_decode(Curl::curlGet($url));
        if (array_key_exists("unionid", $sContent)) {
            // 同过 unionid 去判断用户是否存在
            $user = db("wechat_oauth w")->field("u.user_id as userId,t.token,nickname,head_pic as headPic,mobile")->where("w.unionid", $sContent->unionid)->join("k_users u", "w.user_id = u.user_id")->join("k_api_user_token t", "t.user_id = w.user_id")->find();
            if ($user) {
                //用户存在直接返回用户信息
                $token = md5($user['userId'] . $sContent->unionid . time());
                $tokenData = array(
                    "token" => $token,
                    "time" => time(),
                    "ipaddress" => $_SERVER["REMOTE_ADDR"],
                    "action_token" => $token,
                    "user_id" => $user["userId"]
                );
                $user["token"] = $token;
                db("api_user_token")->where("user_id", $user["userId"])->update($tokenData);
                $this->rest($user);
            } else {
                if (array_key_exists("access_token", $sContent) && array_key_exists("openid", $sContent)) {
                    //用户不存在,获取微信信息并注册返回
                    $weChatUserInfo = $this->getWeChatUserInfo($sContent->access_token, $sContent->openid);
                    $regUser = array(
                        'nickname' => filter_Emoji($weChatUserInfo->nickname),
                        'head_pic' => $weChatUserInfo->headimgurl,
                        'reg_time' => time()
                    );
                    $userId = $this->regUser($regUser);
                    //注册微信token
                    //id, user_id, unionid, openid, create_time, update_time
                    $wechatData = array(
                        'user_id' => $userId,
                        'unionid' => $weChatUserInfo->unionid,
                        'openid' => $weChatUserInfo->openid,
                    );
                    db("wechat_oauth")->insert($wechatData);
                    //注册app_token
                    //id, user_id, token, time, action_token, ipaddress
                    $token = md5(time() . $userId);
                    $tokenData = array(
                        "token" => $token,
                        "time" => time(),
                        "ipaddress" => $_SERVER["REMOTE_ADDR"],
                        "action_token" => $token,
                        "user_id" => $userId
                    );
                    db("api_user_token")->insert($tokenData);
                    $resUser = array(
                        "userId" => $userId,
                        "token" => $token,
                        "nickname" => $weChatUserInfo->nickname,
                        'headPic' => $weChatUserInfo->headimgurl,
                    );
                    $this->rest($resUser);
                } else {
                    $this->rest($sContent);
                }
            }
        } else {
            $this->rest($sContent);
        }

    }

    /**
     * 公众号获取微信用户信息
     */
    private function getWeChatUserInfo($accessToken, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openid";
        $sContent = Curl::curlGet($url);
        return json_decode($sContent);
    }

    /**
     * 用户注册
     * @param $data
     * @return int|string
     */
    private function regUser($data)
    {
        $user = array(
            'username' => '',
            'password' => '',
            'nickname' => $data['nickname'],
            'headurl' => $data['headurl'],
            'age' => '',
            'sex' => $data['sex'],
            'address' => $data['address'],
        );
        $result = db('user')->insertGetId($user);
        $userToken = array(
            'uid' => $result,
            'token' => '',
            'openid_js' => '',
            'openid_app' => '',
            'openid_mini' => $data['openid_mini'],
            'unionid' => '',
        );
        db('user_token')->insert($userToken);
        return $result;
    }

    /**
     * 微信小程序登录
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function getMiniUser()
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        // 参数
        $params['appid'] = 'wx0b6191ff8c31fcc5';
        $params['secret'] = '31c37766bda099af4c15723914604d7b';
        $params['js_code'] = input('code');
        $params['grant_type'] = 'authorization_code';
        // 微信API返回的session_key 和 openid
        $arr = '';
        try {
            $arr = httpWurl($url, $params, 'POST');
            $arr = json_decode($arr, true);
        } catch (\Exception $e) {
            $this->rest('微信请求错误', 's004');
        }
        // 判断是否成功
        if (isset($arr['errcode']) && !empty($arr['errcode'])) {
            $this->rest($arr, 's004');
        }

        $openid = $arr['openid'];
        // 通过openID判断用户是否存在
        $userData = db('user')->alias('u')->field('u.id,u.nickname,u.headurl,ut.token')->join('user_token ut', 'u.id = ut.uid')->where('openid_mini', $openid)->find();
        if (!$userData) {
            $userData = array(
                'nickname' => input('nickname'),
                'headurl' => input('headurl'),
                'openid_mini' => $openid,
                'sex' => input('sex'),
                'address' => input('address'),
            );
            $userId = $this->regUser($userData);
            $userData['id'] = $userId;
        } else {
            $data = array(
                'nickname' => input('nickname'),
                'headurl' => input('headurl'),
            );
            db('user')->where('id', $userData['id'])->update($data);
        }
      /*  $result = array(
            'userId' => $userData['id'],
            'nickName' => $userInfo['nickName'],
            'headUrl' => $userInfo['avatarUrl']
        );*/
        $result = db('user')->where('id', $userData['id'])->find();
        $result['token'] = update_user_token($userData['id']);
        $result['userId'] = $userData['id'];
        $this->rest($result);

    }

    /**
     * 更新用户信息
     * @param $data
     * @return int|string
     */
    public function editUser()
    {
        $uid = $this->isCheckAuth();
        $update = array();
        $nickname = input('nickname');
        if(isset($nickname) && !empty($nickname)){
            $update['nickname'] = $nickname;
        }
        $headurl = input('headurl');
        if(isset($headurl) && !empty($headurl)){
            $update['headurl'] = $headurl;
        }
        $sex = input('sex');
        if(isset($sex) && !empty($sex)){
            $update['sex'] = $sex;
        }
        $age = input('age');
        if(isset($age) && !empty($age)){
            $update['age'] = $age;
        }
        $address = input('address');
        if(isset($address) && !empty($address)){
            $update['address'] = $address;
        }
        $data = db('user')->where('id', $uid)->update($update);
        if($data > 0){
            $this->rest('更新成功');
        }else{
            $this->rest('更新失败','s004');
        }
    }


    /**
     * 用户关注操作
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function follow()
    {
        $uid = input('uid');
        $followId = input('followId');
        $type = input('type');
        if (!$uid || !$followId || !$type) {
            $this->rest('参数错误', 's004');
        }
        if ($type == 2) {
            $this->delFollow($uid, $followId);
        } elseif($type == 1) {
            $this->addFollow($uid, $followId);
        }
    }

    /**
     * 添加关注
     * @param $uid
     * @param $followId
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function addFollow($uid, $followId)
    {
        $data = array(
            'uid' => $uid,
            'follow_id' => $followId,
        );
        //添加前先判断是否关注过该用户
        if (db('user_follow')->where($data)->find()) {
            db('user_follow')->where($data)->setField('status', 1);
            $this->rest('关注成功');
        }
        $data['create_time'] = time();
        $rest = db('user_follow')->insert($data);
        if ($rest) {
            $this->rest('关注成功');
        } else {
            $this->rest('关注失败', 's004');
        }
    }

    /**
     * 取消关注
     * @param $uid
     * @param $followId
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function delFollow($uid, $followId)
    {
        $data = array(
            'uid' => $uid,
            'follow_id' => $followId,
        );
        //添加前先判断是否关注过该用户
        $user = db('user_follow')->where($data)->find();
        if ($user) {
            db('user_follow')->where($data)->setField(['status'=>0,'update_time'=>time()]);
            $this->rest('已取消关注');
        } else {
            $this->rest('取消失败', 's004');
        }
    }



    /**
     * 我的 页面
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function my()
    {
        //$uid = $this->isCheckAuth();
        $uid = input('uid');
        $data = [];
         # 旅说数
        $data['dynamic'] = db('dynamic')->where('uid',$uid)->count();
        # 想去看看
       $data['look'] = db('graded')->where(['state'=>1,'uid'=>$uid])->count();
        #我的关注
        $data['follow'] = db('user_follow')->where('uid',$uid)->count();
        # 旅游足迹
        $data['footprint'] = db('graded')->where(['state'=>2,'uid'=>$uid])->count();
        #我的粉丝
        $data['fans'] = db('user_follow')->where(['status'=>1,'follow_id'=>$uid])->count();

        $this->rest($data);
    }

    /*
     * 我的旅说
     */
    public function mysaid()
    {
        // $uid = $this->isCheckAuth();
        $uid = input('uid');
         $files = 'id,uid,address,content,images,createtime';
         $res = db('dynamic')->field($files)->where(['uid'=>$uid,'del'=>0])->select();
         foreach ($res as $k=>$v){
             $res[$k]['images'] = json_decode($v['images'],true);
             $iscomment = db('comment')->where(['uid'=>$uid,'aid'=>$v['id'],'modular'=>2,'status'=>0])->find();
             if(!empty($iscomment)){
                 $res[$k]['iscomment'] = 1;
             }else{
                 $res[$k]['iscomment'] = 0;
             }
             $islike = db('collection')->where(['uid'=>$uid,'pid'=>$v['id'],'modular'=>'dynamic','status'=>0,'type'=>'like'])->find();
             if(!empty($islike)){
                 $res[$k]['islike'] = 1;
             }else{
                 $res[$k]['islike'] = 0;
             }
             $isshare = db('collection')->where(['uid'=>$uid,'pid'=>$v['id'],'modular'=>'dynamic','status'=>0,'type'=>'share'])->find();
             if(!empty($isshare)){
                 $res[$k]['isshare'] = 1;
             }else{
                 $res[$k]['isshare'] = 0;
             }
             $comment = db('comment')->where(['pid'=>$v['id'],'modular'=>2,'status'=>0])->count();
             $res[$k]['comment']=$comment;
             $likes = db('collection')->where(['pid'=>$v['id'],'modular'=>'dynamic','status'=>0,'type'=>'like'])->count();
             $res[$k]['likes']=$likes;
             $share = db('collection')->where(['pid'=>$v['id'],'modular'=>'dynamic','status'=>0,'type'=>'share'])->count();
             $res[$k]['share'] = $share;
         }
         $this->rest($res);
    }

    /*
     * 1: 我关注的 2:我的粉丝
     */
    public function myfollow()
    {
       // $uid = $this->isCheckAuth();
        $uid = input('uid');
        $type = input('type');
        if(empty($uid) || empty($type)){
            $this->rest('参数错误', 's004');
        }
        $db_uf= db('user_follow')->alias('uf');
        $field = 'uf.uid,uf.follow_id,uf.status,u.nickname,u.headurl,u.sex,u.address,uf.create_time';
        if($type == 1){
            $data = $db_uf->field($field)->join('user u','uf.follow_id=u.id','left')->where(['uf.uid'=>$uid,'uf.status'=>1])->select();
        }else{
            $data = $db_uf->field($field)->join('user u','uf.uid=u.id','left')->where(['uf.follow_id'=>$uid,'uf.status'=>1])->select();
        }
        $this->rest($data);
    }

}